package com.jiwen.service;

import com.jiwen.dao.BackendUserDao;
import com.jiwen.dao.DevUserDao;
import com.jiwen.dto.LoginDto;
import com.jiwen.pojo.BackendUser;
import com.jiwen.pojo.DevUser;
import com.jiwen.util.SysConstant;
import com.jiwen.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author shrstart
 * @create 2023-12-16-9:22
 */

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    DevUserDao devUserDao;

    @Autowired
    BackendUserDao backendUserDao;

    @Override
    public LoginVo userLogin(LoginDto loginDto) {

        LoginVo loginVo = new LoginVo();

        if (loginDto.getUsertype() == 1) {
            /*管理员登陆*/
            BackendUser backendUser = new BackendUser();
            backendUser.setUsercode(loginDto.getAccount());
            backendUser.setUserpassword(loginDto.getPassword());

            List<BackendUser> backendUsers = backendUserDao.queryAllBy(backendUser);
            if (backendUsers.size() != 0) {

                /*设置新token*/
                StringBuffer token = new StringBuffer(UUID.randomUUID().toString().replace("-", ""));
                token.append("-" + System.currentTimeMillis());
                token.append("-" + backendUsers.get(0).getId());
                token.append("-" + SysConstant.UserType.admin);

                loginVo.setUserName(backendUsers.get(0).getUsername());
                loginVo.setUsertype(loginDto.getUsertype());
                loginVo.setToken(token.toString());
            }else{
                loginVo = null;
            }
        } else {
            /*开发者登陆*/
            DevUser devUser = new DevUser();
            devUser.setDevcode(loginDto.getAccount());
            devUser.setDevpassword(loginDto.getPassword());

            List<DevUser> devUsers = devUserDao.queryAllBy(devUser);
            if (devUsers.size() != 0) {

                /*设置新token*/
                StringBuffer token = new StringBuffer(UUID.randomUUID().toString().replace("-", ""));
                token.append("-" + System.currentTimeMillis());
                token.append("-" + devUsers.get(0).getId());
                token.append("-" + SysConstant.UserType.dev);

                loginVo.setUserName(devUsers.get(0).getDevname());
                loginVo.setUsertype(loginDto.getUsertype());
                loginVo.setToken(token.toString());
            }else{
                loginVo = null;
            }
        }

        return loginVo;
    }
}
